package work_wechat

import (
	"context"
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"go-demo-2025/utils/funcUtils"
	"go-demo-2025/utils/redisUtil"
	"time"
)

type WorkWechatConfig struct {
	requestUrl string
	corpId     string
	secret     string
}

func NewWorkWechatConfig() *WorkWechatConfig {
	return &WorkWechatConfig{
		requestUrl: viper.GetString("workWechat.requestUrl"),
		corpId:     viper.GetString("workWechat.corpId"),
		secret:     viper.GetString("workWechat.secret"),
	}
}

// 获取企业微信的access_token
func (ctx *WorkWechatConfig) GetWorkWechatAccessToken() (string, error) {
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%v&corpsecret=%v", ctx.corpId, ctx.secret)
	data, err := funcUtils.HttpGet(url)
	if err != nil {
		errMsg := fmt.Sprintf("GetWorkWechatAccessToken调用三方接口出现了错误: %v", err)
		fmt.Println(errMsg)
		return "", errors.New(errMsg)
	}
	if data["errmsg"] != "ok" {
		errMsg := fmt.Sprintf("GetWorkWechatUserInfo获取到的数据结果异常:%v", data["errmsg"])
		fmt.Println(errMsg)
		return "", errors.New(errMsg)
	}
	if data["access_token"].(string) == "" {
		errMsg := fmt.Sprintf("GetWorkWechatAccessToken获取到的access_token为空")
		fmt.Println(errMsg)
		return "", errors.New(errMsg)
	}
	return data["access_token"].(string), nil
}

// 获取企业微信用户详情
func (ctx *WorkWechatConfig) GetWorkWechatUserInfo(mobile string) (map[string]string, error) {
	//先查redis是否存在企微的AccessToken, 如果不存在再去企微接口获取AccessToken
	var c1 = context.Background()
	workWechatAccessTokenKey := "workWechatAccessTokenKey"
	workWechatAccessTokenVal := redisUtil.GoRdb.Get(c1, workWechatAccessTokenKey).Val()
	if workWechatAccessTokenVal == "" {
		workWechatAccessToken, err := ctx.GetWorkWechatAccessToken()
		if err != nil || workWechatAccessToken == "" {
			return nil, err
		}
		expiration, _ := time.ParseDuration("7000s") //7200-200
		redisUtil.GoRdb.Set(c1, workWechatAccessTokenKey, workWechatAccessToken, expiration)
		workWechatAccessTokenVal = workWechatAccessToken
	}

	//调用企微用户id的接口
	var weworkRequestParams = map[string]string{
		"mobile": mobile,
	}
	url := "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + workWechatAccessTokenVal
	data, err := funcUtils.HttpPost(url, weworkRequestParams, "application/json")
	if err != nil {
		errMsg := fmt.Sprintf("GetWorkWechatUserInfo调用企微接口出现了错误:%v", err)
		fmt.Println(errMsg)
		return nil, errors.New(errMsg)
	}
	if data["errmsg"] != "ok" {
		errMsg := fmt.Sprintf("GetWorkWechatUserInfo获取到的数据结果异常:%v", data["errmsg"])
		fmt.Println(errMsg)
		return nil, errors.New(errMsg)
	}
	if data["userid"].(string) == "" {
		errMsg := fmt.Sprintf("GetWorkWechatUserInfo获取到的userid为空")
		fmt.Println(errMsg)
		return nil, errors.New(errMsg)
	}

	//返回结果
	result := map[string]string{
		"work_wechat_user_id": data["userid"].(string),
	}
	return result, nil
}
